import { View } from "@tarojs/components";
import { getCurrentInstance } from "@tarojs/taro";
import React, { useState, useEffect, useRef } from "react";
import "./index.scss";
import { fetchUserInfo } from "../../api";
import { getOssUrl } from "../../utils";
import { IUserInfo } from "src/interfaces";
import { ImageWithText } from "../img";
import { Logout } from "../../components/logout";

export interface ShareInfoType {
  creatorInfo: {
    img: string;
    name: string;
  };
  companyInfo: {
    img: string;
    name: string;
  };
}

export const ShareHeader = ({
  title,
  shareInfo,
}: {
  title: string;
  shareInfo: ShareInfoType;
}) => {
  const [userInfo, setUserInfo] = useState<IUserInfo>();
  const [isOpenedLogout, setIsOpenedLogout] = useState(false);
  useEffect(() => {
    const { router } = getCurrentInstance();
    const spaceId = router?.params?.spaceId || "";
    if (!spaceId) {
      alert("没有空间id");
      return;
    }
    const init = async () => {
      const [getUserInfoRes] = await Promise.all([fetchUserInfo()]);

      // 用户信息
      if (getUserInfoRes?.code === 0) {
        setUserInfo(getUserInfoRes?.data);
      } else {
        alert(getUserInfoRes?.message);
      }
    };
    init();
  }, []);
  return (
    <div className="share-header">
      <div className="title-container">
        <p className="title">{title}</p>
        {userInfo?.user && (
          <ImageWithText
            className="user-icon"
            src={getOssUrl({
              bucketName: userInfo?.user?.img?.bucketName || "",
              path: userInfo?.user?.img?.path || "",
            })}
            text={userInfo?.user?.nickName}
            onClick={() => {
              setIsOpenedLogout(true);
            }}
          />
        )}
      </div>
      <View className="share-info">
        <ImageWithText
          className="invite-img"
          text={shareInfo?.creatorInfo?.name}
          src={shareInfo?.creatorInfo?.img}
          alt=""
        />
        <div className="right">
          <p className="invite-name">{shareInfo?.creatorInfo?.name}</p>
          <div className="bottom">
            <p>发起者</p>
            <p className="company">
              <ImageWithText
                className="company-icon"
                text={shareInfo?.companyInfo?.name}
                src={shareInfo?.companyInfo?.img}
                alt=""
              />
              <span className="company-name ellipsis">
                {shareInfo?.companyInfo?.name}
              </span>
            </p>
          </div>
        </div>
      </View>
      <Logout isOpened={isOpenedLogout} setIsOpened={setIsOpenedLogout} />
    </div>
  );
};
